<!--
 * @Description: 长来无感结算和余额结算页面
 * @Author: Kerwin
 * @Date: 2025-05-26 14:46:49
 * @LastEditTime: 2025-09-08 10:16:59
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="physicalShopCheck">
    <u-navbar
      :title-bold="false"
      v-if="!isWeChatBrowser"
      :is-back="false"
      color="#333"
      :background="{ backgroundColor: '#f9c9ae' }"
    >
      <template #right>
        <view style="margin: 0 20rpx" @click="clearUser">
          <u-icon name="man-delete" color="#999999" size="42"></u-icon>
        </view>
      </template>
    </u-navbar>
    <!-- 头部 -->
    <view class="topTitLe">
      <view class="leftTitle">
        <view style="font-weight: 700; font-size: 32rpx; margin-bottom: 20rpx"
          >来钡消费总金额</view
        >
        <view style="color: #999">请询问金额后提交</view>
      </view>
      <view class="rightTitle">
        <u-image width="210rpx" height="90rpx" :src="moneyIcon"></u-image>
      </view>
    </view>
    <!-- 商户信息 -->
    <view class="shopBox">
      <text class="name"
        ><u-icon
          size="40"
          style="vertical-align: middle"
          :name="shopIcon1"
        ></u-icon>
        {{ info.name }}</text
      >
      <view class="inptBox">
        <u-input
          v-model="money"
          v-input-decimal2
          type="digit"
          inputmode="decimal"
          focus
          pattern="number"
          placeholder="¥ 0.00"
          input-align="center"
          :custom-style="{
            fontSize: '52rpx'
            // fontWeight: '800'
          }"
          :disabled="inptDisabled"
        />
        <text class="unit">(元)</text>
      </view>
      <view class="yt-list-cell shape2">
        <template v-if="isShowCldyq">
          <view class="cell-tit txbox">
            长来抵用券抵扣：<text class="red"
              >本次最多可抵扣{{ canUseMaxCldyq }}元</text
            ></view
          >
          <view class="cell-tip">
            <view class="wallet">
              长来抵用券剩余：<text class="red">{{
                useTotalChanglaiDyq
              }}</text></view
            >
            <view class="right" style="width: 250rpx">
              <u-input
                class="inputBox"
                :disabled="!useTotalChanglaiDyq && useTotalChanglaiDyq < 0"
                v-input-decimal
                placeholder="请输入抵扣的长来抵用券"
                type="digit"
                v-model="cldyqInput"
                @blur="onScoreChangeLaiDyq"
                :border="true"
              />
            </view>
          </view>
        </template>
        <template v-if="isShowClq">
          <view class="cell-tit txbox">
            现金抵用券抵扣：<text class="red"
              >本次最多可抵扣{{ canUseMaxClq }}元</text
            ></view
          >
          <view class="cell-tip">
            <view class="wallet">
              现金抵用券剩余：<text class="red">{{
                useToatlChanglaiQuan
              }}</text></view
            >
            <view class="right" style="width: 250rpx">
              <u-input
                class="inputBox"
                :disabled="!useToatlChanglaiQuan && useToatlChanglaiQuan < 0"
                v-input-decimal
                placeholder="请输入抵扣的现金抵用券"
                type="digit"
                v-model="clqInput"
                @blur="onScoreChangeLaiQuan"
                :border="true"
              />
            </view>
          </view>
        </template>
        <!-- <view class="cell-tit">
          可用来钡余额：<text class="red">￥{{ clBalance }}</text></view
        > -->
      </view>

      <view
        class="radioBox"
        v-if="info.shopMoneyRules && info.shopMoneyRules.length > 1"
      >
        <u-radio-group
          v-model="moneyRuleId"
          @change="radioGroupChange"
          :wrap="true"
        >
          <u-radio
            v-for="(item, index) in info.shopMoneyRules"
            :key="index"
            :name="item.moneyRuleId"
          >
            {{ item.userMoneyRuleName }}
          </u-radio>
        </u-radio-group>
      </view>
      <!-- <u-form-item label-width="auto" label-position="top" :border-bottom="false" label="付款留言：">
        <u-input style="background-color: #f7f5f5; " :height="200" :border="true" type="textarea"
          v-model="orderData.remark" />
      </u-form-item> -->
    </view>
    <!-- 结算 -->
    <!-- -->
    <u-button
      :disabled="!info.shopId"
      class="hy-btn"
      ripple
      @click="toPayment"
      style="color: white"
      :style="{ backgroundColor: isWeChatBrowser ? '#1ae872' : '#1a73e8' }"
    >
      {{ isWeChatBrowser ? '微信付款' : '支付宝付款' }}
    </u-button>
    <!-- <u-button
      :disabled="!info.shopId"
      class="hy-btn"
      ripple
      type="warning"
      @click="hanleYePay"
    >
      来钡余额付款
    </u-button> -->
    <!-- <u-button @click="handleGoPassword">跳转密码</u-button> -->
    <!-- <u-button @click="handleGoSuccess">去成功</u-button> -->
    <!-- <u-button @click="handleGoBind">跳转绑定</u-button> -->
    <view class="hy-link" v-if="bindPhone" @click="toBindPhone">
      绑定手机号
    </view>
    <!-- 余额密码弹出框 -->
    <van-popup
      v-model:show="showPassword"
      position="bottom"
      round
      :style="{ height: '60%' }"
    >
      <view style="padding: 20rpx">
        <view style="text-align: center; margin-bottom: 20rpx"
          >请输入长来余额密码</view
        >
        <van-password-input
          :value="orderData.payPassword"
          info="密码为 6 位数字"
          :error-info="errorInfo"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <van-number-keyboard
          v-model="orderData.payPassword"
          :show="showKeyboard"
          @blur="showKeyboard = false"
        />
        <view>
          <u-button
            :disabled="
              !orderData.payPassword ||
              orderData.payPassword.length < 6 ||
              isPaying
            "
            type="success"
            style="margin: 20rpx 0"
            @click="onShopMoneyPay"
            :loading="isPaying"
            loading-text="支付中..."
            >确认支付</u-button
          >
          <text @click="handleGoPassword" style="color: #007aff"
            >忘记密码？</text
          >
        </view>
      </view>
    </van-popup>
  </view>
</template>
<script setup lang="ts">
import { Md5 } from 'ts-md5'
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { onLoad, onShow, onLaunch } from '@dcloudio/uni-app'
//存储
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore } from '@/store'
//api
import { enumAll, moneyApi, orderApi, productApi, userApi } from '@/api'
//  组件
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
//工具
import {
  getQueryVariable,
  parseParams,
  getQueryObject,
  isWeChat
} from '@/utils/common'
import debounce from 'lodash/debounce'
//图片
import moneyIcon from '@/static/clMoney.png'
import shopIcon1 from '@/static/hlhy/shopIcon1.png'

//初始数据
const configStore = useConfigStore()
const userStore = useUserStore()
const { enterByStoreQrcode, isWeChatBrowser, isAlipayClient } =
  storeToRefs(configStore)
const { accessToken, useShareCode } = storeToRefs(userStore)
const info = reactive<any>({
  name: '',
  shopId: '',
  shopMoneyRules: []
})
const money = ref()
const orderData = ref<any>({
  remark: ''
})
const productSku = ref()
const flqScore = ref()
const moneyRuleId = ref(null)
const userInfo = userStore.userInfo
const userPhone = ref<any>(null)
const bindPhone = ref(false) //绑定手机号状态
const login_success = ref<any>({ status: false })
const payPassword = ref('') //存储用户密码)
//  用户拥有的总的长来抵用券
const useTotalChanglaiDyq = ref(0)
// 用户拥有的总的现金抵用券
const useToatlChanglaiQuan = ref(0)
// 是否显示长来抵用券
const isShowCldyq = ref(false)
// 是否显示现金抵用券
const isShowClq = ref(false)
const cldyqInput = ref(0)
const clqInput = ref(0)
// 门店让利百分点
const shopPercent = ref(0)
// 长来余额
const clBalance = ref(0)
const errorInfo = ref('')
// 是否显示输入密码弹框
const showPassword = ref(false)
// 是否显示密码数字框
const showKeyboard = ref(true)
// 添加支付状态标志
const isPaying = ref(false) // 防止重复提交
const tempParams = ref<any>(getQueryObject(window.location.search))
// 创建订单
async function creatOrder() {
  console.log('提交的订单信息', orderData.value)
  try {
    const { data } = await orderApi.orderAdd(orderData.value)
    console.log('订单创建成功==>', data)
    if (data) {
      console.log(
        '跳转==>',
        `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
      )
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    }
  } catch (err) {
    console.log(err)
  }
  uni.hideLoading()
}

// 获取长来余额
const getMemberTotalShopMoneyChang = async () => {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.长来余额钱包
  })
  //向下取整保留两位小数
  clBalance.value = Math.floor((Number(data) || 0) * 100) / 100
  console.log(data, '用户的长来余额钱包')
}
// 获取用户总的长来抵用券
async function getMemberTotalClDiYongQuan() {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.长来抵用券
  })
  useTotalChanglaiDyq.value = Math.floor(data * 10) / 10
  console.log(data, '用户拥有的总的长来抵用券')
}
// 获取用户总的现金抵用券
async function getMemberTotalChangLaiQuan() {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.现金抵用券
  })
  useToatlChanglaiQuan.value = Math.floor(data * 10) / 10
  console.log(data, '用户拥有的总的现金抵用券')
}
// 长来抵用券输入框发生改变
const onScoreChangeLaiDyq = (e: number) => {
  e = Number(e)
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请先输入支付金额'
    })
    return
  }
  if (e <= scoreMax.value) {
    cldyqInput.value = e
  } else {
    cldyqInput.value = scoreMax.value
    uni.showToast({
      icon: 'none',
      title: `最多可抵扣长来抵用券￥${scoreMax.value}`
    })
  }
}
// 现金抵用券输入框发生改变
const onScoreChangeLaiQuan = (e: number) => {
  e = Number(e)
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请先输入支付金额'
    })
    return
  }
  if (e <= scoreMax.value) {
    clqInput.value = Math.floor(e)
  } else {
    clqInput.value = Math.floor(scoreMax.value)
    uni.showToast({
      icon: 'none',
      title: `最多可抵扣现金抵用券￥${scoreMax.value}`
    })
  }
}
// 创建防抖版本的 creatOrder 函数，500 毫秒内只执行一次
const debouncedCreatOrder = debounce(creatOrder, 500)
// 跳转密码
const handleGoPassword = () => {
  uni.reLaunch({
    url: `/pages/productCheckout/shopPayPwd?qrcode=${tempParams.value.qrcode}&shopId=${tempParams.value.shopId}&shareCode=${tempParams.value.shareCode}&tzPage=1`
  })
}
// 跳转支付成功页面
const handleGoSuccess = () => {
  uni.reLaunch({
    url: `/pages/physicalShopCheck/clyePaySuccess?qrcode=${tempParams.value.qrcode}&shopId=${tempParams.value.shopId}&shareCode=${tempParams.value.shareCode}&isSmfk=1`
  })
}

async function toPayment() {
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请输入支付金额'
    })
    return
  }
  if (money.value <= 0) {
    uni.showToast({
      icon: 'none',
      title: '最低金额需大于0元'
    })
    return
  }
  if (score_consumption.value > scoreMax.value) {
    uni.showToast({
      icon: 'none',
      title: '最多只能抵扣' + scoreMax.value + '元'
    })
    return
  }

  // uni.showLoading({ title: '', mask: true })
  try {
    await getShopSku()
    // 卖手推荐的门店，卖手获得收益
    // 2023/9/11 扫店铺付款码进入无shareCode则不携带
    if (uni.getStorageSync('shareCode') && useShareCode.value) {
      orderData.value.orderProductSkus[0].externalData = {
        userShareCode: uni.getStorageSync('shareCode')
      }
    }
    // 调用防抖函数
    debouncedCreatOrder()
  } catch (err) {
    uni.hideLoading()
  }
}
// 余额付款的去绑定手机号页面
const handleGoBind = () => {
  uni.navigateTo({
    url: `/pages/physicalShopCheck/clBindPhone?qrcode=${tempParams.value.qrcode}&shopId=${tempParams.value.shopId}&shareCode=${tempParams.value.shareCode}&isSmfk=1`
  })
}
// 长来余额支付按钮
const hanleYePay = async () => {
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请输入支付金额'
    })
    return
  }
  if (money.value <= 0) {
    uni.showToast({
      icon: 'none',
      title: '最低金额需大于0元'
    })
    return
  }
  if (Number(clBalance.value) <= 0) {
    uni.showToast({
      icon: 'none',
      title: '来钡余额不足，不能使用该支付方式'
    })
    return
  }
  if (score_consumption.value > scoreMax.value) {
    uni.showToast({
      icon: 'none',
      title: '最多只能抵扣' + scoreMax.value + '元'
    })
    return
  }
  if (bindPhone.value == true) {
    uni.showModal({
      title: '提示',
      content:
        '您未绑定手机号，使用来钡余额付款需先绑定一次手机号，后续不会再绑定',
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          handleGoBind()
        } else {
        }
      }
    })
    return
  }
  if (payPassword.value == '') {
    uni.showModal({
      title: '提示',
      content:
        '您未设置支付密码，为确保支付安全需先设置一次支付密码，后续不会再设置',
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          handleGoPassword()
        } else {
        }
      }
    })
    return
  }
  // 判断长来余额大于实付款
  if (
    Number(money.value) <= Number(clBalance.value + score_consumption.value)
  ) {
    showPassword.value = true
  } else {
    uni.showToast({
      icon: 'error',
      title: '来钡余额不足！'
    })
    return
  }
  // 获取orderProductStku数据
  await getShopSku()
}
// 长来余额支付确认按钮
const onShopMoneyPay = async () => {
  // 防止重复点击
  if (isPaying.value) return
  console.log(
    'orderData.value.payPassword',
    orderData.value.payPassword,
    orderData.value.payPassword.length
  )

  // 设置支付中状态
  isPaying.value = true
  orderData.value.shopMode = 6
  orderData.value.moneyUnit = '长来余额钱包'
  console.log('待提交的数据', orderData.value)
  uni.showLoading({ title: '支付中请等候', mask: true })
  try {
    const { data, code, mes } = await orderApi
      .orderAdd({
        ...orderData.value,
        // 不能直接将加密的支付密码赋值给orderData的payPassword，这样回导致点击确认支付后无法再删除密码
        payPassword: Md5.hashStr(orderData.value.payPassword)
      })
      .finally(() => {
        uni.hideLoading()
        isPaying.value = false // 无论成功失败都重置状态
      })
    if (code == 200) {
      uni.showToast({
        icon: 'success',
        title: '来钡余额支付成功！'
      })
      orderData.value.payPassword = ''
      showPassword.value = false
      handleGoSuccess()
    } else {
      orderData.value.payPassword = ''
      showPassword.value = false
      uni.showToast({
        icon: mes,
        title: '来钡余额支付失败！'
      })
    }
  } catch (e) {
    orderData.value.payPassword = ''
    console.log('来钡余额支付error', e)
    isPaying.value = false
  }
}

//获取商铺sku
const getShopSku = async () => {
  const { data } = await productApi.getShopProductSkuList({
    detail: false,
    dynamicPrice: true,
    shopId: info.shopId
  })
  if (data.records) {
    productSku.value = data.records[0]
    orderData.value.orderProductSkus = [
      {
        count: 1,
        money: money.value,
        shopProductSkuId: productSku.value.id,
        moneyRuleId: moneyRuleId.value,
        dynamicPric: true
      }
    ]
    orderData.value.scoreMoney = score_consumption.value
  }
}

//获取用户信息
const getUserDetailInfo = async () => {
  try {
    const { data } = await userApi.userInfo()
    console.log('用户数据', data)

    if (data && data.phone) {
      userPhone.value = data.phone
    } else {
      userPhone.value = '' // 确实没有手机号时设为空字符串
    }
    // 是否有密码
    if (data.payPassword) {
      payPassword.value = data.payPassword
    } else {
      payPassword.value = ''
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    userPhone.value = '' // 出错时也设为空字符串
  }
}

const isHjfShop = ref(false) // 是否花积分
const isflqShop = ref(false) // 是否复来券
const userScore = ref(0) // 用户积分余额
const hjfUserScor = ref(0) //花积分的积余额
const maxUserScor = ref(0) //固定积分上限

let _userScore = 0

//查询让利规则
const getRule = async () => {
  console.log(productSku.value, 5555)

  const { data } = await moneyApi.getProductDeductionMaxMoney({
    shopProductSkuId: productSku.value.id,
    detail: false
  })
  console.log(data, 666)
  flqScore.value = data.rate
}

//计算最多可以使用的长来抵用券
const canUseMaxCldyq = computed(() => {
  if (!isShowCldyq.value) {
    return 0
  }
  if (!orderData) return 0
  if (money.value) {
    let _money = 0
    // 规则：金额的一半
    _money = money.value / 2
    let calculateMoney = 0
    // 计算最多可以抵扣的长来抵用券
    if (_money > useTotalChanglaiDyq.value) {
      calculateMoney = Math.floor(useTotalChanglaiDyq.value * 10) / 10
    } else {
      calculateMoney = Math.floor(_money * 10) / 10
    }
    cldyqInput.value = calculateMoney
    return calculateMoney
  } else {
    return 0
  }
})
// 计算最多可以使用的现金抵用券
const canUseMaxClq = computed(() => {
  if (!orderData) return 0
  if (money.value) {
    let _money = 0
    // 都乘以100是为了解决浮点数精度问题
    // 门店的让利点
    const num1 = shopPercent.value * 100
    // 1%的平台费
    const num2 = 0.01 * 100
    // 规则：金额*（门店让利点-1%平台费）
    _money = (money.value * (num1 - num2)) / 100
    let calculateMoney = 0
    // 计算最多可以抵扣的现金抵用券
    if (_money > useToatlChanglaiQuan.value) {
      calculateMoney = Math.floor(useToatlChanglaiQuan.value)
    } else {
      calculateMoney = Math.floor(_money)
    }
    clqInput.value = calculateMoney
    return calculateMoney
  } else {
    return 0
  }
})
// 计算可以抵扣的金额，会随着优惠券输入框的值变化而变化
const score_consumption = computed(() => {
  if (isShowCldyq.value) {
    return cldyqInput.value
  } else if (isShowClq.value) {
    return clqInput.value
  } else {
    return 0
  }
})
// 计算最多可抵扣的金额
const scoreMax = computed(() => {
  if (isShowCldyq.value) {
    return canUseMaxCldyq.value! // 断言不为 undefined
  } else if (isShowClq.value) {
    return canUseMaxClq.value! // 断言不为 undefined
  } else {
    return 0
  }
})

async function getShopInfo() {
  const { data } = await productApi.getShopInfo({
    id: info.shopId,
    detail: true,
    otherColumns: 'moneyRuleDetails'
  })
  const { name, shopMoneyRules, code, user, integralsRuleId } = data
  uni.setStorageSync('shopCode', code)
  uni.setStorageSync('shopOwnerShareCode', user.shareCode)
  info.name = name
  if (shopMoneyRules && shopMoneyRules.length > 0) {
    if (moneyRuleId.value) {
      // 判断url携带的moneyRuleId是否还存在（可能规则已删除，但是码或者链接存在滞后）
      const rule = shopMoneyRules.find(
        (item: { moneyRuleId: null }) => item.moneyRuleId == moneyRuleId.value
      )
      if (!rule) {
        info.shopMoneyRules = shopMoneyRules
        moneyRuleId.value = shopMoneyRules[0].moneyRuleId
      }
    } else {
      info.shopMoneyRules = shopMoneyRules
      moneyRuleId.value = shopMoneyRules[0].moneyRuleId
    }
  }
  if (moneyRuleId.value) {
    // 判断是否显示长来抵用券
    if (20116 <= moneyRuleId.value && moneyRuleId.value <= 20120) {
      isShowCldyq.value = true
    } else if (20203 <= moneyRuleId.value && moneyRuleId.value <= 20220) {
      // 判断是否显示现金抵用券
      isShowClq.value = true
    }
    // 根据moneyRuleId后两位得到，如20103得到0.03，20111得到0.11，提取最后两位数字（通过取余100实现）再转换为小数（除以100）
    shopPercent.value = (moneyRuleId.value % 100) / 100
  }
}
watch(accessToken, (newValue, oldValue) => {
  getShopInfo()
})
watch(money, (newValue, oldValue) => {
  if (newValue) {
    nextTick(() => {
      money.value = newValue.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })
    if (newValue < 0) {
      uni.showToast({
        icon: 'none',
        title: '金额不能小于0'
      })
      money.value = 0
    } else {
    }
  }
})

//跳转到绑定手机号·
const toBindPhone = () => {
  //将当前url存在本地
  uni.setStorageSync('currentUrl', window.location.href)
  uni.navigateTo({
    url: '/pages/physicalShopCheck/bindPhone'
  })
}

function radioGroupChange(e: any) {
  console.log(e)
}

//清空用户信息
const clearUser = () => {
  userStore.syncClearToken()
  userStore.syncClearUserInfo()
  uni.navigateTo({
    url: `/pages/physicalShopCheck/hlhyPay?qrcode=${tempParams.value.qrcode}&shopId=${tempParams.value.shopId}&shareCode=${tempParams.value.shareCode}`
  })
}

const honbaoStatus = ref(false)
const inptDisabled = ref(false)
const btnColor = ref('2979ff')
const maxRetryCount = 3 // 设置最大重试次数
let retryCount = 0 // 当前重试次数

// 初始化逻辑
onShow(() => {
  console.log('进入onSHOW')
})

onLoad(async (option: any) => {
  console.log('长来无感支付', option)
  // 待删除的代码
  // getUserDetailInfo()
  // getMemberTotalShopMoneyChang()
  // getMemberTotalClDiYongQuan()
  // getMemberTotalChangLaiQuan()
  // getMes(option)

  retryCount = 0 // 重置重试次数
  // 微信浏览器
  if (isWeChatBrowser.value) {
    honbaoStatus.value = true
    // 待还原的代码
    await handleAuth(option, handleWeChatAuth)
  } else {
    // 其他浏览器
    // 监听登录状态变化
    const unwatch = watch(
      () => userStore.hasLogin,
      (newVal) => {
        if (newVal) {
          getMes(option)
          getUserDetailInfo()
          getMemberTotalShopMoneyChang()
          getMemberTotalClDiYongQuan()
          getMemberTotalChangLaiQuan()
          unwatch() // 取消监听
        }
      },
      { immediate: true }
    )
    // 如果未登录，跳转到登录页
    if (!userStore.hasLogin) {
      uni.navigateTo({
        url: `/pages/login/index?qrcode=${tempParams.value.qrcode}&shopId=${tempParams.value.shopId}&shareCode=${tempParams.value.shareCode}`
      })
    }
  }
})

// 获取店铺信息
function getMes(option: any) {
  if (!option) return

  const { shopId, moneyRuleId, money, color, deviceCode } = option
  info.shopId = shopId || ''
  info.deviceCode = deviceCode || ''
  moneyRuleId && (moneyRuleId.value = moneyRuleId)
  money && ((money.value = money), (inptDisabled.value = true))
  color && (btnColor.value = color)

  getShopInfo()
}

// 处理授权和登录逻辑
async function handleAuth(
  option: any,
  authMethod: (option: any) => Promise<void>
) {
  try {
    console.log('支付宝授权处理1', retryCount, option)

    await authMethod(option)
    // 授权成功后重置 retryCount
    retryCount = 0
  } catch (error) {
    handleAuthError(error, option, authMethod)
  }
}
// 处理支付宝授权和登录
async function handleAlipayAuth(option: any) {
  console.log('授权处理', retryCount)
  const user_id = await userStore.aliAuth()
  console.log('用户ID:', user_id)
  const openid = user_id

  login_success.value = await userStore.hlhyLoginByOpenId(openid)
  console.log(login_success.value, '用户登录是否成功', option)

  if (!login_success.value.status) {
    throw new Error('登录失败')
  }

  console.log(userInfo, '用户信息')
  // updateBindPhoneStatus(login_success.value)

  // 只在登录成功时调用 getMes
  console.log('传递的optins--》', option)
  getMes(option)
}

// 处理微信授权和登录
async function handleWeChatAuth(option: any) {
  console.log('进入无感支付微信授权', option, 'xxxx')

  await userStore.wxAuth()

  const codeAuth = getQueryVariable('code')
  console.log('微信授权码', codeAuth)

  if (!codeAuth) {
    login_success.value = { status: false }
    throw new Error('获取微信授权码失败')
  }

  await userStore.wxWebLogin(codeAuth) //获取openid
  const result: any = await userStore.hlhyLoginByOpenId()
  login_success.value = result // 保存登录结果
  console.log('授权成功吗?===>', result)

  if (!result.status) {
    throw new Error('登录失败')
  }

  console.log(userInfo, '用户信息', result.status)
  getUserDetailInfo()
  // 只在登录成功时调用
  console.log('传递的optins--》', option)
  getMes(option)
  getMemberTotalShopMoneyChang()
  getMemberTotalClDiYongQuan()
  getMemberTotalChangLaiQuan()
}

// 监听 login_success.status
watch(
  () => login_success.value.status,
  (newStatus) => {
    if (newStatus) {
      // 登录成功后检查手机号
      getUserDetailInfo()
    } else {
      // 登录失败时不显示绑定手机号
      bindPhone.value = false
    }
  },
  { immediate: true }
)

watch(
  userPhone,
  (newPhone) => {
    if (login_success.value.status) {
      if (newPhone === null) {
        // 还未获取用户信息，不显示绑定按钮
        bindPhone.value = false
      } else {
        // 已获取用户信息，根据是否有手机号决定是否显示绑定按钮
        bindPhone.value = !newPhone || newPhone.trim() === ''
      }
    }
  },
  { immediate: true }
)
// 处理授权错误（调整条件判断）
function handleAuthError(
  error: any,
  option: any,
  authMethod: (option: any) => Promise<void>
) {
  console.error('授权或登录失败:', error, userStore.hasLogin)

  let errorMessage = '授权或登录失败，请重试'
  if (error?.errorDesc) errorMessage = error.errorDesc

  uni.showToast({ title: errorMessage, icon: 'none' })

  // 主要调整：不依赖 userStore.hasLogin，直接根据重试次数判断
  console.log(retryCount, '失败次数')

  if (retryCount < maxRetryCount) {
    retryCount++
    uni.showModal({
      title: '授权失败',
      content: `剩余 ${maxRetryCount - retryCount} 次重试机会`,
      success: (res) => {
        if (res.confirm) handleAuth(option, authMethod)
      }
    })
  } else {
    uni.showToast({ title: '授权失败次数过多，请稍后重试', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.physicalShopCheck {
  padding: 30rpx;
  text-align: center;
  background: linear-gradient(#fab791 0%, rgba(255, 250, 224, 0) 30%);

  .topTitLe {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .leftTitle {
      text-align: left;
    }
  }

  .shopBox {
    // margin: 0 10rpx;
    min-height: 300rpx;
    padding: 20rpx;
    background: url('@/static/pay1.png') no-repeat;
    background-size: 100% 100%;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1); // 外部阴影

    .name {
      text-align: center;
      margin-top: 20rpx;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .inptBox {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding: 20rpx 0;
    border-top: 1px solid #8080802e;
    border-bottom: 1px solid #8080802e;
    position: relative;
    margin-top: 40rpx;
    font-size: 50rpx;

    .unit {
      right: 0;
      top: 36rpx;
      font-size: 28rpx;
      margin-bottom: 10rpx;
    }
  }

  .yt-list-cell {
    display: flex;
    align-items: center;
    padding: 40rpx 0;
    position: relative;

    .cell-tit {
      flex: 1;
      font-size: 26rpx;
      // color: #909399;
      margin-top: 20rpx;
      text-align: left;
    }

    &.shape2 {
      display: block;

      .cell-tip {
        display: flex;
        justify-content: space-between;
        margin-top: 20rpx;
        align-items: center;
        width: 600rpx;

        .wallet {
          font-size: 28rpx;
          // color: #ff6c18;
        }
      }
    }
  }
  .hjfScore {
    margin-top: 10rpx;
    text-align: left;
    color: #909399;
  }

  .radioBox {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;

    :deep(.u-radio) {
      justify-content: center;
    }
  }

  .hy-btn {
    margin-top: 50rpx;
  }
  .hy-link {
    margin-top: 30rpx;
    text-align: right;
    color: #ea4824;
    //下划线
    text-decoration: underline;
    // font-size: 24rpx;
  }
}

.inputBox {
}
.red {
  color: #ff6c18;
}
.txbox {
  display: flex;
  align-items: center;
}
</style>
